<template>
  <el-container style="height: 1100px; border: 1px solid #eee">
    <el-main>
      <router-view/>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-card class="box-card">
                <el-row>
                  <el-col :span="5" style="background-color: #818589;display: flex">
                    <div style="width: 100% ;height: 100% ;display: flex">
                      <el-image :src="circleUrl" :fit="fit"></el-image>
                    </div>
                  </el-col>
                  <el-col :span="5">
                    <el-card style="height: 230px">
                      <el-row :gutter="15">
                        <p style="text-align: left; font-size: 20px; margin-bottom: 20px">{{name}} &nbsp;
                          <el-tag key="空闲"
                                  type="success"
                                  effect="dark"
                                  style="padding-bottom: 5px;right: 10px "
                          >
                            空闲
                          </el-tag>  </p>
                      </el-row>

                      <el-row :gutter="15" style="margin-top: 30px">
                        <el-button type="primary">设置</el-button>
                      </el-row>

                    </el-card>

                  </el-col>
                  <el-col :span="14"><div class="grid-content bg-purple">
                    <el-card class="box-card" style="height: 230px">
                      <el-space :size="size" :spacer="spacer">
                        <div class="cardme" style=" width:220px;text-align: center ">
                          <p class="title1">今日咨询数</p>
                          <p class="digit3">{{countToday}}</p>
                        </div>
                        <div class="cardme"  style=" width:220px;text-align: center ">
                          <p class="title1">今日咨询时长</p>
                          <p class="digit3">{{timeToday}}<span style="font-size: 12px;color: gray;font-weight: lighter;">分钟</span></p>
                        </div>
                      </el-space>
                    </el-card>
                  </div></el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16"><div class="grid-content bg-purple">

              <el-card class="box-card">
                <table>
                  <tr>
                    <td style="font-family: 'Microsoft YaHei', sans-serif;font-weight: bold ">在线咨询师 </td>
                    <td style="width: 90px;">&nbsp;</td>
                    <td><el-pagination
                        background
                        layout="prev, pager, next"
                        :total="dataList2.length"
                        :page-size="pageSize"
                        @current-change="paging"
                    >
                    </el-pagination></td>
                  </tr>
                </table>
                <el-table :data="dataList2.slice((currentPage-1)*pageSize,currentPage*pageSize)" max-height="160">
                  <el-table-column  prop="userAvatar" width="50" align="center">
                    <template #default="scope" >
                      <el-avatar :src="scope.row.userAvatar"></el-avatar>
                    </template>
                  </el-table-column>
                  <el-table-column label="咨询师" prop="name" width="190" align="center"></el-table-column>
                  <el-table-column label="状态" prop="status" width="190" fixed="right" align="center"
                                   :filters="[{ text: '空闲', value: '空闲' }, { text: '忙碌', value: '忙碌' }]"
                                   :filter-method="filterTag"
                                   filter-placement="bottom-end">
                    <template #default="scope">
                      <el-tag
                          :type="scope.row.status === '空闲' ? 'success' : 'danger'"
                          disable-transitions
                      >{{scope.row.status}}</el-tag
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div></el-col>
            <el-col :span="8" style="background-color: #2c3e50">

              <el-card class="box-card" style="background-color: #2c3e50; color: #ffffee; border:0">
                <p class="title2">当前会话数</p>
                <p class="digit2">{{curSess}}</p>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="10">
          <el-card class="box-card" style="height: 100%">
            <el-calendar style="background: #eef7ff">
              <template #dateCell="{data}">
                <p :class="(value.includes(new Date(data.day).getDay()) ||dutyDay.includes(new Date(data.day).getDate()))&&new Date(data.day).getMonth()===new Date().getMonth()  ? '✔️' : ''">
                  {{ data.day.split('-').slice(2).join() }} {{ (value.includes(new Date(data.day).getDay())||dutyDay.includes(new Date(data.day).getDate()))&&new Date(data.day).getMonth()===new Date().getMonth() ? '✔️' :
                    '' }}
                </p>
              </template>
            </el-calendar>
          </el-card>

        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24"><div class="grid-content bg-purple-dark">
          <p class="title2">最近求助</p>
          <el-table :data="dataList" style="font-size: 16px" :header-cell-style="discountHeaderStyle">
            <el-table-column type="index"
                             :index="indexFn"
                             prop="id"
                             label="No." width="100" align="center">
            </el-table-column>
            <el-table-column prop="id" width="1" align="center" v-if="false"></el-table-column>
            <el-table-column  prop="userAvatar" width="50" align="center">
              <template #default="scope" >
                <el-avatar :src="scope.row.userAvatar"></el-avatar>
              </template>
            </el-table-column>
            <el-table-column label="咨询师" prop="name" width="180" align="center">
            </el-table-column>
            <el-table-column prop="time" label="咨询时间" width="200" align="center">
            </el-table-column>
            <el-table-column prop="duration" label="时长" width="350" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button icon="el-icon-search" circle @click="HandleDrawer(scope.row.id)"></el-button>
                <el-button type="success" icon="el-icon-download" circle @click="recordDownload(scope.row.id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div></el-col>
      </el-row>
      <el-drawer :title="drawerName" v-model="drawerVisible" :with-header="false">
        <span style="width: 150px"><el-button type="text" @click="getMoreMess(drawerName)">查看更多</el-button></span>
        <el-table id="eltable" :show-header="false" :data="mList" :height="800">
          <el-table-column prop="message" align="left" >
            <template #default="scope" >
              <span style="font-size: 12px;color:gray;font-weight: lighter" v-if="scope.row.message!==''">  {{scope.row.time}}</span>

              <el-row>
                <el-avatar :src="'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'" v-if="scope.row.message!==''"></el-avatar>
                &nbsp; &nbsp;
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-if="scope.row.message!=='' && scope.row.type === 'text'">
                  {{scope.row.message}}
                </el-card>
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-else-if="scope.row.message!==''  && scope.row.type === 'pic'">
                  <el-image :src="scope.row.message"></el-image>
                </el-card>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="mine">
            <template #default="scope" style="float: right">
              <el-row align="right" style="float: right">
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-if="scope.row.mine!==''  && scope.row.type === 'text'">
                  {{scope.row.mine}}
                </el-card>
                <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-else-if="scope.row.mine!==''  && scope.row.type === 'pic'">
                  <el-image :src="scope.row.mine"></el-image>
                </el-card>
                &nbsp; &nbsp;
                <el-avatar :src="'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'" v-if="scope.row.mine!==''"></el-avatar>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </el-main>
  </el-container>
</template>

<script>
import { h, resolveComponent } from 'vue'
import { ElDivider } from 'element-plus'
import tim from "../../tim";
import TIM from "_tim-js-sdk@2.17.1@tim-js-sdk/tim-js-friendship";
function offTime (value) {
  var v = value;
  var date = new Date(v * 1000);
  var Y = date.getFullYear() + "-";
  var M =
      (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
  var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var h =
      (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var m =
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let dt = new Date(Date.parse(new Date()));
  let current = dt.getFullYear() + "-" + dt.getMonth() + "-" + dt.getDate();
  let system = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
  if (current === system) {
    return h + m;
  } else {
    return M + D;
  }
}
const circleUrl = 'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'
export default {
  name: "TutorMe",
  data() {
    return {
      name:'',
      count:0,
      timeTotal:0,
      countToday:0,
      timeToday:0,
      curSess:0,
      drawerVisible: false,
      drawerName: '',
      conversationList:[],
      nextReqMessageID:'',
      isCompleted:false,
      mList:[],
      size: 10,
      fit:'fill',
      rating:3.7,
      currentPage:1,
      pageSize:2,
      spacer: h(ElDivider, { direction: 'vertical',height:'5em' }),
      dataList:[

      ],
      dataList2:[
        {
          name:'testcons3',
          userAvatar:circleUrl,
          status:'空闲'
        },
        {
          name:'testcons4',
          userAvatar:circleUrl,
          status:'空闲'
        },
        {
          name:'qwx',
          userAvatar:circleUrl,
          status:'空闲'
        },
        {
          name:'qwx123',
          userAvatar:circleUrl,
          status:'空闲'
        },
      ],
      page:0,
      dialogVisible:false,
      dialogVisible2:false,
      doctor: {},
      digit:16342,
      value: [2,4],
      dutyDay:[],
      monthcnt:5,
      searchForm:{},
      chartData1:[],
      chartData2:[],
      drawer: false,

      circleUrl:'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'
    }
  },
  mounted() {

  },methods:{
    HandleDrawer(name) {
      const _this = this
      _this.drawerVisible = true
      _this.drawerName = name
      _this.mList = []
      _this.nextReqMessageID = ''
      _this.isCompleted = false
      _this.getMess(15, name,'')
    },
    getMess(count, chatName, nextSeq) {
      const _this = this
      let promise2 = tim.getMessageList({
        conversationID: 'C2C' + chatName,
        nextReqMessageID:nextSeq,
        count: 15,
      });
      promise2.then(function (imResponse) {
        let tempList=[]
        for (const item of imResponse.data.messageList) {
          let m = ''
          let time = offTime(item.time)
          if (item.type === "TIMImageElem"){
            let m = item.payload.imageInfoArray[0].imageUrl
            if (item.from === String(chatName)) {
              tempList.push({time:time,message: m, mine: '',type:'pic'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'pic'})
            }
          }else{
            if (item.cloudCustomData === 'user') {
              m = '用户：\n '+item.payload.text
            } else if (item.cloudCustomData === 'consultant') {
              m = '咨询师：\n '+item.payload.text
            } else if (item.cloudCustomData === 'askhelp') {
              m = '----督导介入---- : '
            } else {
              m = item.payload.text
            }
            if (item.from === String(chatName)) {
              tempList.push({time:time,message: m, mine: '',type:'text'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'text'})
            }
          }
        }
        tempList = tempList.concat(_this.mList)
        _this.mList = tempList
        _this.nextReqMessageID = imResponse.data.nextReqMessageID
        _this.isCompleted = imResponse.data.isCompleted
        console.log(imResponse)
      });
    },
    getMoreMess(chatName){
      const _this = this
      if (_this.isCompleted===false){
        _this.getMess(15,chatName,_this.nextReqMessageID)
      }
    },
    async getMessForAll(chatName) {
      const _this = this
      let res = []
      let next = ''
      let nextSeq = ''
      let isCompl = false
      let cnt = 0
      while (isCompl===false){
        await tim.getMessageList({
          conversationID: 'C2C' + chatName,
          nextReqMessageID: nextSeq,
          count: 15,
        }).then(function (imResponse) {
          let tempList = []
          for (const item of imResponse.data.messageList) {
            let m = ''
            let time = offTime(item.time)
            if (item.type === "TIMImageElem"){
              let m = '[图片]'
              if (item.from === String(chatName)) {
                tempList.push({time:time,message: m, mine: '',type:'pic'})
              } else {
                tempList.push({time:time,message: '', mine: m,type:'pic'})
              }
            }else{
              if (item.cloudCustomData === 'user') {
                m = '用户：\n '+item.payload.text
              } else if (item.cloudCustomData === 'consultant') {
                m = '咨询师：\n '+item.payload.text
              } else if (item.cloudCustomData === 'askhelp') {
                m = '----督导介入---- : '
              } else {
                m = item.payload.text
              }
              if (item.from === String(chatName)) {
                tempList.push({time:time,message: m, mine: '',type:'text'})
              } else {
                tempList.push({time:time,message: '', mine: m,type:'text'})
              }
            }
          }
          tempList = tempList.concat(res)
          res = tempList
          nextSeq = imResponse.data.nextReqMessageID
          isCompl = imResponse.data.isCompleted
          console.log(res)
        })
      }
      console.log(res)
      return res
    },
    recordDownload(chatName){
      let res = []
      this.getMessForAll(chatName).then(data=>{
        res = data
        const downName = chatName+'_'+Math.floor(Math.random()*100000)
        let title = ['时间','用户'+chatName,'咨询师'+window.sessionStorage.getItem('username')]
        let key = ['time','message','mine']
        clickDownload(data,downName,title,key)
      })

    },
    paging(val){
      const _this = this
      _this.currentPage = val
    },
    indexFn(index){
      index = (index+1)+(this.currentPage-1)*this.pageSize
      return index
    },
    filterTag(value, row) {
      return row.status === value
    },

    handleAdd(s){

    },

    handleQuery(id){

    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then((_) => {
            done()
          })
          .catch((_) => {})
    },


  },
  async created() {
    const _this = this
    let userId = window.sessionStorage.getItem('userid')
    let userSig = window.sessionStorage.getItem('usersig')
    _this.name = window.sessionStorage.getItem('name')
    let dateMonth = new Date().getMonth()+1
    let dateYear = new Date().getFullYear()
    await _this.$axios.get('http://106.14.247.163:8080/supervisor/getSupervisorById/'+userId).then(resp=>{
      _this.count = resp.data.data.supervisorInfo.countTotal
      _this.timeTotal = resp.data.data.supervisorInfo.timeTotal
      _this.countToday = resp.data.data.countToday
      _this.timeToday = resp.data.data.timeToday
      _this.curSess = resp.data.data.currentSession
    })
    await _this.$axios.get('http://106.14.247.163:8080/supervisor/getRelatedOnlineConsultants/'+userId).then(resp=>{
      let data = resp.data.data
      _this.dataList2=[]
      for (let item of data){
        _this.dataList2.push({name:item.userInfo.userName,userAvatar:circleUrl,status:item.state})
      }
    })
    await _this.$axios.get('http://106.14.247.163:8080/duty/getDutyByUid/'+userId+'/'+dateYear+'/'+dateMonth).then(resp=>{

      for (let item of resp.data.data){
        let days = item.dutyDate.split('-')
        _this.dutyDay.push(parseInt(days[2]))
      }
      console.log(_this.dutyDay)
    })
    _this.$axios.get('http://106.14.247.163:8080/supervisor/getDefaultDuty/'+userId).then(resp=>{
      _this.duty = resp.data.data.defaultDuty
    }).catch(err=>{
      console.warn(err)
    })
    await _this.$axios.get('http://106.14.247.163:8080/supervisor/getHelpRecords/'+userId).then(resp=>{
      console.log(resp)
      _this.dataList = []
      let cnt = 0
      for (let item of resp.data.data.reverse()){
        if (cnt>5){break}
        _this.dataList.push({
          id:item.consultant.userInfo.userId,
          name:item.consultant.userInfo.userName===null?'无':item.consultant.userInfo.userName,

          userAvatar: circleUrl,
          duration: item.recordInfo.duration === null ? 0 : item.recordInfo.duration,
          time: item.recordInfo.datetime === null ? '1970-01-01' : item.recordInfo.datetime.slice(0, 10),
        })
        cnt++;
      }
    })
    let promise = tim.login({userID:userId,userSig:userSig})
    promise.then((imResponse)=>{
      console.log(imResponse.data);
    }).catch((imError)=>{
      console.warn(imError)
    })
    tim.on(TIM.EVENT.SDK_READY, function(event) {
      let promise1 = tim.getConversationList();
      promise1.then(function (imResponse){
        _this.conversationList = imResponse.data.conversationList;
        console.log(_this.conversationList[0].conversationID)
      }).catch(function (imError){
        console.warn(imError)
      })
    });
  },
  destroyed() {
    // 离开页面退出当前账号
    let promise = this.tim.logout();
    // promise
    //   .then(function (imResponse) {
    //     console.log(imResponse.data);
    //   })
    //   .catch(function (imError) {
    //     console.warn("logout error:", imError);
    //   });
  }
}
function clickDownload(data,fileName,title,key){
  JSonToCSV.setDataConver({
    data: data,
    fileName: fileName,
    columns: {
      title: title,//csv表头
      key: key,//json字段
      formatter: function(n, v) {
        if(n === 'avg_click_user_cnt') {
          return Number(v).toFixed(2);
        }
        if(v === undefined){
          return " ";
        }
      }
    }
  });
}
//csv下载
(function( global, factory ) {
  "use strict";
  if(typeof module === "object" && typeof module.exports === "object" ) {
    module.exports = global.document ?
        factory( global, true ) :
        function(w) {
          return factory(w);
        };
  } else {
    factory(global);
  }
})(window, function(){
  var JSonToCSV = {
    /*
     * obj是一个对象，其中包含有：
     * ## data 是导出的具体数据
     * ## fileName 是导出时保存的文件名称 是string格式
     * ## showLabel 表示是否显示表头 默认显示 是布尔格式
     * ## columns 是表头对象，且title和key必须一一对应，包含有
          title:[], // 表头展示的文字
          key:[], // 获取数据的Key
          formatter: function() // 自定义设置当前数据的 传入(key, value)
     */
    setDataConver: function(obj) {
      var bw = this.browser();
      if(bw['ie'] < 9) return; // IE9以下的
      var data = obj['data'],
          ShowLabel = typeof obj['showLabel'] === 'undefined' ? true : obj['showLabel'],
          fileName = (obj['fileName'] || 'UserExport') + '.csv',
          columns = obj['columns'] || {
            title: [],
            key: [],
            formatter: undefined
          };
      var ShowLabel = typeof ShowLabel === 'undefined' ? true : ShowLabel;
      var row = "", CSV = '', key;
      // 如果要现实表头文字
      if (ShowLabel) {
        // 如果有传入自定义的表头文字
        if (columns.title.length) {
          columns.title.map(function(n) {
            row += n + ',';
          });
        } else {
          // 如果没有，就直接取数据第一条的对象的属性
          for (key in data[0]) row += key + ',';
        }
        row = row.slice(0, -1); // 删除最后一个,号，即a,b, => a,b
        CSV += row + '\r\n'; // 添加换行符号
      }
      // 具体的数据处理
      data.map(function(n) {
        row = '';
        // 如果存在自定义key值
        if (columns.key.length) {
          columns.key.map(function(m) {
            row += '"' + (typeof columns.formatter === 'function' ? columns.formatter(m, n[m]) || n[m] : n[m]) + '",';
          });
        } else {
          for (key in n) {
            row += '"' + (typeof columns.formatter === 'function' ? columns.formatter(key, n[key]) || n[key] : n[key]) + '",';
          }
        }
        row.slice(0, row.length - 1); // 删除最后一个,
        CSV += row + '\r\n'; // 添加换行符号
      });
      if(!CSV) return;
      this.SaveAs(fileName, CSV);
    },
    SaveAs: function(fileName, csvData) {
      var bw = this.browser();
      if(!bw['edge'] && !bw['ie']) {
        var alink = document.createElement("a");
        alink.id = "linkDwnldLink";
        alink.href = this.getDownloadUrl(csvData);
        document.body.appendChild(alink);
        var linkDom = document.getElementById('linkDwnldLink');
        linkDom.setAttribute('download', fileName);
        linkDom.click();
        document.body.removeChild(linkDom);
      }
      else if(bw['ie'] >= 10 || bw['edge'] == 'edge') {
        var _utf = "\uFEFF";
        var _csvData = new Blob([_utf + csvData], {
          type: 'text/csv'
        });
        window.navigator.msSaveBlob(_csvData, fileName);
      }
      else {
        var oWin = window.top.open("about:blank", "_blank");
        oWin.document.write('sep=,\r\n' + csvData);
        oWin.document.close();
        oWin.document.execCommand('SaveAs', true, fileName);
        oWin.close();
      }
    },
    getDownloadUrl: function(csvData) {
      var _utf = "\uFEFF"; // 为了使Excel以utf-8的编码模式，同时也是解决中文乱码的问题
      if (window.Blob && window.URL && window.URL.createObjectURL) {
        var csvData = new Blob([_utf + csvData], {
          type: 'text/csv'
        });
        return URL.createObjectURL(csvData);
      }
      // return 'data:attachment/csv;charset=utf-8,' + _utf + encodeURIComponent(csvData);
    },
    browser: function() {
      var Sys = {};
      var ua = navigator.userAgent.toLowerCase();
      var s;
      (s = ua.indexOf('edge') !== - 1 ? Sys.edge = 'edge' : ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1]:
          (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
              (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                  (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                      (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                          (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
      return Sys;
    }
  };
  window.JSonToCSV = JSonToCSV;
});
</script>

<style lang="css" scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row  :last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #f1f1f1;
}
.bg-purple {
  background: #f1f1f1;
}
.bg-purple-light {
  background: #f1f1f1;

}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.title1 {
  font-family: "PingFang SC",sans-serif;
  font-size: 16px;
  color: gray;
  line-height: 1.5;
  font-weight: normal;
}
.title2 {
  font-family: "PingFang SC",sans-serif;
  font-size: 16px;
  color: white;
  line-height: 1.0;
  font-weight: normal;
}
.digit1 {
  font-family: "Microsoft YaHei",sans-serif;
  font-weight: bold;
  font-size: 36px;
  line-height:2.0;
  color: #06386a;
}
.digit2 {
  font-family: "Microsoft YaHei",sans-serif;
  font-weight: bold;
  color: white;
  font-size: 48px;
  line-height:2.0;
}
.digit3{
  font-family: "Microsoft YaHei",sans-serif;
  font-weight: bold;
  font-size: 36px;
  line-height:2.5;
  color: #06386a;
}
.line1 {
  height: 400px;
}
#myChart {
  background: #e1f1ff;
}
.box-card /deep/ .el-calendar-table .el-calendar-day{
  height: 58px;
}
.table1 .td{
  padding: 0 !important;
  height: 40px;
  line-height: 40px;
}
.special{
  background-color: #081542;
}

.cardme{
  border:0;
}

.el-divider{
  display:inline-block;
  width:1px;
  height:5em;
  margin:0 8px;
  vertical-align:middle;
  position:relative;
}

#eltable{
  --el-table-border: 0px;
  --el-table-row-hover-background-color: none;
}

</style>